from django.db import models
from django.utils import timezone
from django.db import connection

# Create your models here.

# 超市管理器
class SupermarketManager(models.Manager):
    """自定义超市管理器"""
    
    def get_active(self):
        """获取所有营业中的超市"""
        return self.filter(status=1)
    
    def get_nearby(self, latitude, longitude, radius=10.0):
        """获取附近的超市
        
        使用简单的地理距离计算，返回指定半径内的超市
        latitude, longitude - 用户位置坐标
        radius - 搜索半径(公里)
        """
        from django.db.models import F, Func, ExpressionWrapper, FloatField
        from django.db.models.functions import ACos, Cos, Sin, Radians
        
        # 地球半径(公里)
        R = 6371.0
        
        # 计算距离的SQL表达式
        distance_expr = ExpressionWrapper(
            R * ACos(
                Cos(Radians(latitude)) * Cos(Radians(F('latitude'))) * 
                Cos(Radians(F('longitude')) - Radians(longitude)) +
                Sin(Radians(latitude)) * Sin(Radians(F('latitude')))
            ),
            output_field=FloatField()
        )
        
        # 查询并按距离排序
        queryset = self.filter(status=1).annotate(
            distance=distance_expr
        ).filter(
            distance__lte=radius
        ).order_by('distance')
        
        return queryset

# 超市模型
class Supermarket(models.Model):
    """
    超市模型 (对应数据库tb_supermarket表)
    
    使用Django的ORM但不创建表，而是映射到现有表
    """
    market_id = models.BigAutoField(primary_key=True)
    name = models.CharField(max_length=100, verbose_name='超市名称')
    address = models.CharField(max_length=255, null=True, blank=True, verbose_name='地址')
    longitude = models.DecimalField(max_digits=10, decimal_places=6, null=True, blank=True, verbose_name='经度')
    latitude = models.DecimalField(max_digits=10, decimal_places=6, null=True, blank=True, verbose_name='纬度')
    image_url = models.CharField(max_length=255, null=True, blank=True, verbose_name='超市图片URL')
    business_hours = models.CharField(max_length=100, null=True, blank=True, verbose_name='营业时间')
    phone = models.CharField(max_length=20, null=True, blank=True, verbose_name='联系电话')
    description = models.TextField(null=True, blank=True, verbose_name='超市描述')
    rating = models.DecimalField(max_digits=2, decimal_places=1, default=5.0, verbose_name='评分')
    sale_count = models.IntegerField(default=0, verbose_name='销售总量')
    status = models.SmallIntegerField(default=1, verbose_name='状态')
    create_time = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    # 自定义管理器
    objects = SupermarketManager()
    
    class Meta:
        managed = False  # 声明该模型不由Django管理表的创建和删除
        db_table = 'tb_supermarket'  # 指定映射到的数据库表名
        app_label = 'market'
        verbose_name = '超市'
        verbose_name_plural = '超市'
        
    def __str__(self):
        return self.name
    
    def get_box_count(self):
        """获取超市盲盒数量"""
        from blindbox.models import BlindBox
        return BlindBox.objects.filter(market_id=self.market_id, status=1).count()
    
    def get_boxes(self, limit=None):
        """获取超市盲盒"""
        from blindbox.models import BlindBox
        boxes = BlindBox.objects.filter(market_id=self.market_id, status=1)
        
        # 如果有指定数量限制，则返回指定数量的盲盒
        if limit:
            boxes = boxes[:limit]
        
        return boxes
    
    @property
    def status_display(self):
        """状态显示文本"""
        return '营业中' if self.status == 1 else '休息中'

    def get_reviews(self, limit=None):
        """获取超市评价
        
        由于当前系统中不存在 tb_market_review 表，我们暂时返回空列表
        """
        # 返回空列表作为临时解决方案
        return []

class SupermarketApplication(models.Model):
    """
    超市申请模型 (对应数据库tb_supermarket_application表)
    """
    application_id = models.BigAutoField(primary_key=True)
    name = models.CharField(max_length=100)
    address = models.CharField(max_length=255, null=True, blank=True)
    business_hours = models.CharField(max_length=50, null=True, blank=True)
    status = models.CharField(max_length=20, default='pending')
    latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
    longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
    image_url = models.CharField(max_length=255, null=True, blank=True)
    remark = models.TextField(null=True, blank=True)
    contact_name = models.CharField(max_length=50, null=True, blank=True)
    contact_phone = models.CharField(max_length=20, null=True, blank=True)
    create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)
    apply_time = models.DateTimeField(null=True, blank=True)
    
    class Meta:
        managed = False
        db_table = 'tb_supermarket_application'
        app_label = 'market'
        verbose_name = '超市申请'
        verbose_name_plural = '超市申请'
        
    def __str__(self):
        return self.name
